package com.young4h.xinsuiwutuobang.bean.test;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
 * 	InvocationHandler
 *  is the interface implemented by the invocation handler of a proxy instance.
 *  Each proxy instance has an associated invocation handler.
 *  When a method is invoked on a proxy instance, the method
 *  invocation is encoded and dispatched to the invoke method
 *  of its invocation handler.
 *  简单的说明就InvocationHandler是一个通过代理实例的调用处理的接口实现，每一个
 *  代理实例都有一个关联的调用处理
 * @author 杨飞
 *
 */
public class DynamicProxy implements InvocationHandler {
	private Object target;	
	
	public DynamicProxy(Object target) {
		this.target = target;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		before();
		Object result = method.invoke(target, args);
		after();
		return result;
	}
	public void before(){
		System.out.println("before");
	}
	public void after(){
		System.out.println("after");
	}
	public static void main(String[] args) {
		Hello hello = new HelloImpl();
		DynamicProxy proxy = new DynamicProxy(hello);
		Hello helloProxy =proxy.getProxy();
		helloProxy.sayHello("xiaoming");
	}
	@SuppressWarnings("unchecked")
	public <T> T getProxy(){
		return (T) Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
	}
}
